import { useTradingView } from '@/stores/tradingVIew.ts';
import { makeApiRequest, generateSymbol, parseFullSymbol } from './helpers.js';
import { useKline } from '@/stores/kline';
// let kline = useKline()

class detaFeed {
    constructor(vue) {
        this.self = vue
        console.log(vue)
        // //this.self.currentPair.priceDisplayDp
        // this.barsUpdater = new dataUpdater(this)
    }
    configurationData = {
        // Represents the resolutions for bars supported by your datafeed
        "has_intraday": true,
        // supported_resolutions:kline.tradingViewTime,
        supported_resolutions: ["1", "5", "15", "30", "1H", "4H", "1D", "1W"],
        supports_marks: true,
        supports_time: true,
        supports_timescale_marks: true,

        // "supported_resolutions": ["1D", "2W", "5M"],
        // "intraday_multipliers": ["1", "2"],
        // The `exchanges` arguments are used for the `searchSymbols` method if a user selects the exchange
        exchanges: [
            { value: 'Binance', name: 'Binance', desc: 'Binance bitcoin exchange' },
            // { value: 'Bitfinex', name: 'Bitfinex', desc: 'Bitfinex'},
            // { value: 'Kraken', name: 'Kraken', desc: 'Kraken bitcoin exchange'},

        ],
        // The `symbols_types` arguments are used for the `searchSymbols` method if a user selects this symbol type
        symbols_types: [
            { name: 'crypto', value: 'crypto' }
        ]
    }
    chartData = []

    async getAllSymbols() {
        // const data = await makeApiRequest('data/v3/all/exchanges');
        const data = await makeApiRequest('/api/stream/pair/list');
        // console.log(data.data, "responseresponse")

        let allSymbols = [];
        let pairs = {}
        for (const exchange of this.configurationData.exchanges) {
            data.data.map((item) => {
                let tradingSymbol = ''
                tradingSymbol = item.symbol.replace('USDT', '');
                item.tradingSymbol = tradingSymbol
                pairs[tradingSymbol] = ['USDT'];
            })
            // const pairs = data.Data[exchange.value].pairs;
            // debugger
            for (const leftPairPart of Object.keys(pairs)) {
                const symbols = pairs[leftPairPart].map(rightPairPart => {
                    const symbol = generateSymbol(exchange.value, leftPairPart, rightPairPart);
                    const dataItem = data.data.filter(dItem => dItem.tradingSymbol == leftPairPart)
                    return {
                        symbol: symbol.short,
                        ticker: symbol.full,
                        description: symbol.short,
                        exchange: exchange.value,
                        type: 'crypto',
                        priceDisplayDp: dataItem[0].priceDisplayDp,

                    };
                });
                allSymbols = [...allSymbols, ...symbols];
            }
        }
        return allSymbols;
    }
    subscribeBars(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) {
        console.log('[subscribeBars]: Method call with subscriberUID:', symbolInfo, subscriberUID);
        // 限制单例
        // tradingView.subscriberList = window.kChartSubscriberList || []

        // 避免重复订阅
        // const found = tradingView.subscriberList.some(n => n.uid === subscriberUID)
        // if (found) return
        let tradingView = useTradingView()

        // 添加订阅
        tradingView.subscriberList = {
            symbol: symbolInfo,
            resolution: resolution,
            uid: subscriberUID,
            callback: onRealtimeCallback
        }
        this.self.subscribeBars(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback)

        console.log(tradingView.subscriberList)
    }
    async resolveSymbol(
        symbolName,
        onSymbolResolvedCallback,
        onResolveErrorCallback,
        extension
    ) {
        console.log('[resolveSymbol]: Method call', symbolName);
        const symbols = await this.getAllSymbols();
        const symbolItem = symbols.find(({ ticker }) => {
            if (symbolName.includes('Binance')) {
                return ticker === symbolName
            } else {
                return ticker === 'Binance:' + symbolName
            }
            // ticker === symbolName
        });
        console.log('symbolItem', symbolItem, symbolName, symbols);

        if (!symbolItem) {
            console.log('[resolveSymbol]: Cannot resolve symbol', symbolName);
            onResolveErrorCallback('Cannot resolve symbol');
            return;
        }
        //  symbolItem.symbol = symbolItem.symbol.replace("/", "");
        // Symbol information object
        const zeros = "0".repeat(symbolItem.priceDisplayDp);
        const pricescale = parseInt(`1${zeros}`);
        const symbolInfo = {
            ticker: symbolItem.ticker,
            name: symbolItem.symbol,
            description: symbolItem.description,
            type: symbolItem.type,
            session: '24x7',
            timezone: 'Etc/UTC',
            exchange: symbolItem.exchange,
            minmov: 1,
            pricescale: pricescale,
            has_intraday: true,
            visible_plots_set: 'ohlc',
            has_weekly_and_monthly: true,
            supported_resolutions: this.configurationData.supported_resolutions,
            volume_precision: 2,
            data_status: 'streaming',

        };
        console.log('[resolveSymbol]: Symbol resolved', symbolName);
        onSymbolResolvedCallback(symbolInfo);
    }
    async getBars(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) {
        console.log(this.self)
        const { from, to, firstDataRequest } = periodParams;
        console.log('[getBars]: Method call', symbolInfo, resolution, periodParams, from, to);
        const parsedSymbol = parseFullSymbol(symbolInfo.ticker);
        console.log(symbolInfo, resolution, periodParams, parsedSymbol, "parsedSymbolparsedSymbol")
        this.self.getBars(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback, parsedSymbol)

        // let isMore = false

        // // debugger
        // const urlParameters = {
        //     e: "Binance",
        //     fsym: parsedSymbol.fromSymbol,
        //     tsym: parsedSymbol.toSymbol,
        //     toTs: to,
        //     limit: 2000,
        // };
        // let data = ''

        // const query = Object.keys(urlParameters)
        //     .map(name => `${name}=${encodeURIComponent(urlParameters[name])}`)
        //     .join('&');
        // try {
        //     // const data = await makeApiRequest(`data/histoday?${query}`);
        //     if (firstDataRequest) {
        //         data = await makeApiRequest(`/api/stream/bar/${parsedSymbol.fromSymbol}USDT/list?interval=D1&limit=1000`);

        //     } else {
        //         data = await makeApiRequest(`/api/stream/bar/${parsedSymbol.fromSymbol}USDT/list?interval=D1&limit=1000&endTime=${this.chartData[0]?.time || ''}`);

        //     }
        //     // chartData=data
        //     if (!data.success || data.data.length === 0) {
        //         // "noData" should be set if there is no data in the requested period
        //         onHistoryCallback([], { noData: true });
        //         return;
        //     }
        //     let bars = [];
        //     data.data.forEach(bar => {
        //         if ((bar.startTime / 1000) >= from && (bar.startTime / 1000) < to) {
        //             // console.log(bar)
        //             bars = [...bars, {
        //                 time: bar.startTime,
        //                 low: bar.low,
        //                 high: bar.high,
        //                 open: bar.open,
        //                 close: bar.close,
        //             }];
        //         }
        //     });
        //     this.chartData = bars
        //     // debugger
        //     console.log(`[getBars]: returned ${bars.length}${data.data.length} bar(s)`, bars, from, bars, to);
        //     // debugger
        //     if (data.data.length < 1000) {
        //         isMore = true
        //         console.log("没有更多数据了", isMore)
        //     }
        //     console.log(bars, "barsbars")
        //     onHistoryCallback(bars, { noData: isMore });
        // } catch (error) {
        //     console.log('[getBars]: Get error', error);
        //     onErrorCallback(error);
        // }
    }
    // getResolutionConfig() {
    //     return {
    //         "1": { minutes: 1 },
    //         "5": { minutes: 5 },
    //         "15": { minutes: 15 },
    //         "30": { minutes: 30 },
    //         "60": { minutes: 60 },
    //         "D": { minutes: 1440 },
    //         "W": { minutes: 10080 },
    //         "M": { minutes: 43200 }
    //     };
    // }
    async searchSymbols(
        userInput,
        exchange,
        symbolType,
        onResultReadyCallback
    ) {
        console.log('[searchSymbols]: Method call');
        const symbols = await this.getAllSymbols();
        const newSymbols = symbols.filter(symbol => {
            const isExchangeValid = exchange === '' || symbol.exchange === exchange;
            const isFullSymbolContainsInput = symbol.ticker
                .toLowerCase()
                .indexOf(userInput.toLowerCase()) !== -1;
            return isExchangeValid && isFullSymbolContainsInput;
        });
        onResultReadyCallback(newSymbols);
    }
    onReady(callback) {
        // let ctype = localStorage.getItem("K_TYPE");
        // if (ctype) {
        //     kline.changeCurCoinByName(ctype);
        // }
        // else {
        //     kline.changeCurCoin(kline.map[0]);
        // }
        // console.log(kline.tradingViewTime)
        // console.log('[onReady]: Method call');
        setTimeout(() => callback(this.configurationData));
    }
    unsubscribeBars(subscriberUID) {
        // console.log('[unsubscribeBars]: Method call with subscriberUID:', subscriberUID);
    }
    getMarks(symbolInfo, startDate, endDate, onDataCallback, resolution) {
        // //如果事件需要实时更新，就修改成setInterval
        // console.log(startDate,endDate,"endDateendDate")
        // onDataCallback(
        //     [
        //         {
        //             id: 1,
        //             time: new Date().getTime()/1000-70,
        //             color: 'red',
        //             text: ['This is the mark pop-up text.'],
        //             label: 'M',
        //             labelFontColor: 'blue',
        //             minSize: 25
        //         },
        //         {
        //             id: 2,
        //             time: endDate + 5260000, // 2 months
        //             color: 'red',
        //             text: ['Second marker'],
        //             label: 'S',
        //             labelFontColor: 'green',
        //             minSize: 25
        //         }
        //     ]);
        // console.log(symbolInfo, startDate, endDate, onDataCallback, resolution)
        // debugger
        // var marks = _this_.getMarks();
        // setTimeout(()=>{
        //     // console.log(marks,5566)
        //     onDataCallback(marks);
        // },0);
    };
    getTimescaleMarks = (
        symbolInfo,
        startDate,
        endDate,
        onDataCallback,
        resolution
    ) => {
        // optional
        // console.log(startDate, endDate, 'getTimescaleMarks11');

        let tradingView = useTradingView()
        tradingView.maskList = {
            symbol: symbolInfo,
            resolution: resolution,
            callback: onDataCallback
        }
    };
}
export default detaFeed
